from absl import app, flags
import pandas as pd

from coin.support.proto_log.logic.util import enumerate_og_log_into_oginfos
from coin.base.datetime_util import convert_string_to_dates
from coin.exchange.base.order_gateway_logger import parse_file_name_from_coin2
from xunkemgmt_client.tool.slack_noti import send_to_slack
from xunkemgmt_client.client.util.query_util import query_accounts


FLAGS = flags.FLAGS


def _check_log_not_archived(account_info_from_archive):
  diff = []
  acct_info_from_db = query_accounts(active=True, business_units=['Coin'], as_proto=True)
  acct_info_set = set([(acct_info.market_type, acct_info.exchange, acct_info.owner) for acct_info
                         in account_info_from_archive])
  for acct_info in acct_info_from_db:
    if (acct_info.market_type, acct_info.exchange, acct_info.owner) not in acct_info_set:
      diff.append({'market_type': acct_info.market_type,
                   'exchange':acct_info.exchange,
                   'owner': acct_info.owner})
  diff_msg = ''
  if len(diff) != 0:
    diff_df = pd.DataFrame(diff)
    diff_msg = '\nAccounting log not archived:\n' + \
               diff_df.sort_values(by=['market_type', 'exchange']).to_string()
  return diff_msg


def _check_log_not_registered(account_info_from_archive):
  diff = []
  account_list = query_accounts(as_proto=True)
  active_acct_list = set([(acct.market_type, acct.exchange, acct.owner) for acct in account_list])
  for acct_info in account_info_from_archive:
    if (acct_info.market_type, acct_info.exchange, acct_info.owner) not in active_acct_list:
      diff.append({'market_type': acct_info.market_type,
                   'exchange':acct_info.exchange,
                   'owner': acct_info.owner})
  diff_msg = ''
  if len(diff) != 0:
    diff_df = pd.DataFrame(diff)
    diff_msg = '\nAccounting log not registered:\n' + \
               diff_df.sort_values(by=['market_type', 'exchange']).to_string()
  return diff_msg


def _check_archive(trading_date, root_dir, slack_receiver):
  td_str = trading_date.strftime('%Y%m%d')
  acct_info_from_archive = enumerate_og_log_into_oginfos(
      root_dir, td_str, parse_file_name_from_coin2)
  msg = f'{root_dir}:\n'
  msg += '%s' % _check_log_not_archived(acct_info_from_archive)
  msg += '%s' % _check_log_not_registered(acct_info_from_archive)
  print(msg)
  if slack_receiver is not None:
    msg = '```' + msg + '```'
    send_to_slack(msg, slack_receiver, 'msg')


def main(_):
  assert FLAGS.trading_date
  trading_date = convert_string_to_dates(FLAGS.trading_date)[0]
  _check_archive(trading_date, FLAGS.root_dir, FLAGS.slack_receiver)


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, 'Trading date in form of %Y%m%d.')

  flags.DEFINE_string('root_dir', '/remote/iosg/strat-1/buckets/log.raw.coin/live//account_proto_log', '')

  flags.DEFINE_string('slack_receiver', None, 'slack_receiver')
  
  app.run(main)
